package com.javatip.project.Controller;

import com.javatip.common.utils.HardwareInfo;
import com.javatip.project.interceptor.RegistrationCodeInterceptor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.FileWriter;
import java.io.IOException;

@Controller
public class RegistrationController {

    @GetMapping("/register")
    public String register(Model model, HttpSession session) {
//        // 如果已经验证成功，重定向到登录页面
//        if (RegistrationCodeInterceptor.isVerified) {
//            return "redirect:/login";
//        }
//
//        String applicationCode = HardwareInfo.generateApplicationCode();
//        model.addAttribute("getApplicationCode", applicationCode);
        return "register";
    }

    @PostMapping("/register")
    public String validateRegistrationCode(@RequestParam String registrationCode, RedirectAttributes redirectAttributes, HttpSession session) {
//        String applicationCode = HardwareInfo.generateApplicationCode();
//
//        if (HardwareInfo.validateRegistrationCode(applicationCode, registrationCode) || RegistrationCodeInterceptor.isVerified) {
        session.setAttribute("registrationSuccess", true);
//            RegistrationCodeInterceptor.isVerified = true;
//
//            // 获取当前路径
//            String currentPath = System.getProperty("user.dir");
//            // 存储注册码的位置
//            String registrationCodePath = currentPath + "/src/main/resources/Validation/registrationCode.txt";
//            // 写入注册码到文件
//            try {
//                FileWriter writer = new FileWriter(registrationCodePath);
//                writer.write(registrationCode);
//                writer.close();
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
        return "redirect:/login";
        //} else {
//            session.setAttribute("registrationSuccess", false);
//            redirectAttributes.addFlashAttribute("error", "注册失败，注册码无效。");
//            return "redirect:/register";
//        }
    }
}
